#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import androidhelper
import sendtomailbox
import time
#sendmail= sendtomailbox.Sendtomail()
droid = androidhelper.Android()
#a=droid.smsGetMessagesById(10)

def getWifi():
#'''获取并返回wifi信息 '''
    wifi=droid.wifiGetConnectionInfo().result
    try:
#        return "\nWIFI: "+wifi['ssid']+" BSSID: "+wifi['bssid']+"\n"
        return "WIFI: %s BSSID: %s \n" %(wifi['ssid'],wifi['bssid'])
    except KeyError:
    #wifi 未连接时没有bssid，程序会抛出KeyError
        return "WIFI is not connected!\n"

        
def getBattery():
#'''获取并返回电池信息'''

    plugtype=[' 未充电',' 交流电充电中',' USB充电中','充电口状态未知']
    droid.batteryStopMonitoring()
    droid.batteryStartMonitoring()
    battpercent=droid.batteryGetLevel().result
    plug=droid.batteryGetPlugType().result
    droid.batteryStopMonitoring()
    if not type(plug):
        plug=-1
    return "电量: %d %s" %(battpercent,plugtype[plug])
    
def getTime(datestamp_):

#'''获取并返回短信时间'''
    datestamp=float(datestamp_)/1000
    fmtdate=time.strftime("%Y/%m/%d %H:%M:%S",time.localtime(datestamp))
    return "%s\n"%(fmtdate)
    
    
    
def main():
    acount=len(droid.smsGetMessages(unreadOnly=1).result)
#获得未读短信数量，大于1则发送邮件
    if acount:
        if acount>1:
            print('You got %d new messages.'%(acount))
        else:
            print('You got %d new message.'%(acount))

        a=droid.smsGetMessages(unreadOnly=1).result
        while acount:
            adict=a[acount-1]
  
            #print(adict['body'])
            alist=[adict['_id']]
            MailContent="%s\n\n\t\t%s\n📱\n%s%s"%(adict['body'],getTime(adict['date']),getWifi(),getBattery())
            #字符串格式化 is very good!
            timenow=time.asctime( time.localtime(time.time()) )
            print(timenow,'\n',MailContent)
            if sendtomailbox.Sendtomail(MailContent,adict['address']):
                droid.smsMarkMessageRead(alist,1)
            
            acount=acount-1

try:
    
    timenow=time.asctime( time.localtime(time.time()) )
    print('\n%s 启动程序...'%(timenow))
    startmsg="%s\nPhone Status:\n%s%s"%(timenow,getWifi(),getBattery())
    
    sendtomailbox.Sendtomail(startmsg,'Service starts.')
    t=0
    heart=0
    while 1:
    
        main()
        t+=1
        #等待十秒
        if t%360==0:
            heart+=1
            timenow=time.asctime(time.localtime(time.time()))
            sendtomailbox.Sendtomail(timenow,'Heart beat %d \n%d'%(heart,t))
        
        time.sleep(10)
        
        
except KeyboardInterrupt:
 
    droid.batteryStopMonitoring()
    timenow=time.asctime(time.localtime(time.time()))
    stopmsg=" ❗ ️ \n%s\nPhone Status:\n%s%s"%(timenow,getWifi(),getBattery())
    sendtomailbox.Sendtomail(stopmsg,'Service stops normaly.')
    print('\n%s 程序正常结束...'%(timenow))
        
